package com.keray.common.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

/**
 * 图片旋转工具类
 */
public class RotateImage {


    /**
     * 对图片进行旋转
     *
     * @param src   被旋转图片
     * @param angel 旋转角度
     * @return 旋转后的图片
     */
    public static BufferedImage rotate(Image src, int angel) {
        int src_width = src.getWidth(null);
        int src_height = src.getHeight(null);
        // 计算旋转后图片的尺寸
        Rectangle rect_des = calcRotatedSize(new Rectangle(new Dimension(
                src_width, src_height)), angel);
        BufferedImage res = null;
        res = new BufferedImage(rect_des.width, rect_des.height,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = res.createGraphics();
        // 进行转换
        g2.translate((rect_des.width - src_width) / 2,
                (rect_des.height - src_height) / 2);
        g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);

        g2.drawImage(src, null, null);
        return res;
    }

    /**
     * 计算旋转后的图片
     *
     * @param src   被旋转的图片
     * @param angel 旋转角度
     * @return 旋转后的图片
     */
    public static Rectangle calcRotatedSize(Rectangle src, int angel) {
        // 如果旋转的角度大于90度做相应的转换
        if (angel >= 90) {
            if (angel / 90 % 2 == 1) {
                int temp = src.height;
                src.height = src.width;
                src.width = temp;
            }
            angel = angel % 90;
        }

        double r = Math.sqrt(src.height * src.height + src.width * src.width) / 2;
        double len = 2 * Math.sin(Math.toRadians(angel) / 2) * r;
        double angel_alpha = (Math.PI - Math.toRadians(angel)) / 2;
        double angel_dalta_width = Math.atan((double) src.height / src.width);
        double angel_dalta_height = Math.atan((double) src.width / src.height);

        int len_dalta_width = (int) (len * Math.cos(Math.PI - angel_alpha
                - angel_dalta_width));
        int len_dalta_height = (int) (len * Math.cos(Math.PI - angel_alpha
                - angel_dalta_height));
        int des_width = src.width + len_dalta_width * 2;
        int des_height = src.height + len_dalta_height * 2;
        return new Rectangle(new Dimension(des_width, des_height));
    }


    public static BufferedImage generate(HttpServletRequest request, HttpServletResponse response, java.util.List<String> urls) throws IOException {
        if (CollUtil.isEmpty(urls)) {
            throw new RuntimeException();
        }
        int angel = RandomUtil.randomInt(5, 360);
        String sessionId = UUIDUtil.generateUUIDByTimestamp();
        long time = System.currentTimeMillis();
        Cookie cookie = new Cookie("image-code-uuid", sessionId);
        cookie.setPath("/");
        response.addCookie(cookie);
        cookie = new Cookie("image-code-time", String.valueOf(time));
        cookie.setPath("/");
        response.addCookie(cookie);
        cookie = new Cookie("image-code-md5", DigesterUtil.MD5Encode(sessionId + time + angel));
        cookie.setPath("/");
        response.addCookie(cookie);
        String url = urls.get(RandomUtil.randomInt(0, urls.size()));
        return RotateImage.rotate(ImageIO.read(new URL(url)), angel);
    }

    public static boolean imageCodeCheck(int angel, HttpServletRequest request) {
        String sessionId = getCookieValue(request.getCookies(), "image-code-uuid");
        String timeStr = getCookieValue(request.getCookies(), "image-code-time");
        Long time = timeStr == null ? null : Long.valueOf(timeStr);
        // 超出5分钟无效
        if (time == null || time < System.currentTimeMillis() - 5 * 60 * 1000) {
            return false;
        }
        String md5 = getCookieValue(request.getCookies(), "image-code-md5");
        // 允许10度的误差
        for (int i = angel - 5; i < angel + 5; i++) {
            if (DigesterUtil.MD5Encode(sessionId + time + (360 - i)).equalsIgnoreCase(md5)) {
                return true;
            }
            if (DigesterUtil.MD5Encode(sessionId + time + (-i)).equalsIgnoreCase(md5)) {
                return true;
            }
        }

        return false;
    }

    private static String getCookieValue(Cookie[] cookies, String key) {
        if (cookies == null) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(key)) {
                return cookie.getValue();
            }
        }
        return null;
    }
}
